// graceUI/components/graceTree.js
Component({
  properties: {
    trees : {type:Array, value:function () {return [];}},
		indent : {type:Number, value:28},
		level  : {type:Number, value:0},
		lineHeight  : {type:String, value:'80rpx'},
		fontSize  : {type:String, value:'28rpx'},
		fontColor : {type:String, value:'#323232'},
		type : {type:String, value:'text'},
		isIcon : {type:Boolean, value:true},
		iconSize:{type:String, value:'30rpx'},
		indexes : {type:Array, value:['',0]},
		checkedId : {type:[String, Number], value:'-1'},
		checkedIds : {type:Array, value: []},
		checkedColor:{type:String, value:'#3688FF'},
		allCanCheck: {type:Boolean, value:true},
		isFold : {type:Boolean, value:true}
  },
  data: {
    treesIN:[],
		indexesIn : [],
		notids:[]
  },
  ready:function(){
    this.setData({treesIN : this.data.trees});
		if(this.data.indexes[0] != ''){
			var indexes  =  this.data.indexes[0].split(',');
		}else{
			var indexes = [];
		}
		indexes.push(this.data.indexes[1]);
    this.data.indexesIn = indexes.join(',');
		this.setData({indexesIn : this.data.indexesIn});
		watch(this,{
      type : function(nv, ov){
        this.setData({notids : []});
      }
    });
  },
  methods: {
		fold  : function (e) {
			var id            = e.currentTarget.dataset.id;
			if(this.data.isFold){
				var res = this.arrayIndexOf(this.data.notids, id);
				if(res == -1){
					this.data.notids.push(id);
				}else{
					this.data.notids.splice(res,1);
				}
				this.setData({notids:this.data.notids});
			}
		},
    taped : function(e){
			var havsons       = e.currentTarget.dataset.havsons;
			var treeindexs    = e.currentTarget.dataset.treeindexs;
			treeindexs        = treeindexs.split(',');
			var index         = e.currentTarget.dataset.index;
			var id            = e.currentTarget.dataset.id;
			treeindexs.push(index);
			treeindexs.shift();
			if(this.data.type == 'text'){
				this.tapbase(treeindexs);
			}else{
				var cancheck = e.currentTarget.dataset.cancheck;
				if(cancheck){this.tapbase(treeindexs);}
			}
			
		},
		tapbase : function(e){
      if(e.detail){e = e.detail;}
			this.triggerEvent('taped', e);
		},
		setTrees : function (trees) {
      this.setData({treesIN : trees});
		},
		arrayIndexOf : function(arr, needFind){
			var index = -1;
			for(let i = 0; i < arr.length; i++){
				if(arr[i] == needFind){index = i; return i;}
			}
			return index;
		}
  }
});

function defineReactive(data, key, val, fn) {
  Object.defineProperty(data, key, {
    configurable: true,
    enumerable: true,
    get: function () {return val},
    set: function (newVal) {
      if (newVal === val) return;
      fn && fn(newVal);
      val = newVal;
    },
  })
}
function watch(ctx, obj) {
  Object.keys(obj).forEach(key => {
    defineReactive(ctx.data, key, ctx.data[key], function (value) {obj[key].call(ctx, value)});
  })
}
